<?php
class service_image{
	public function insert($imgs,$typeID,$itemID=0,$url=''){
		if(!empty($imgs)){
			$imgDao = new DaoImage();
			$now = date("Y-m-d H:i:s");
			foreach($imgs as $img){
				$item = array();
				$item['typeID'] = $typeID;
				$item['itemID'] = $itemID;
				$item['src'] = $img;
				$item['url'] = $url;
				$item['createTime'] = $item['updateTime'] = $now;
				$imgDao->insert($item);
			}
		}
	}
	public function getBig($path){
		if(strpos($path,"/big")){
			return $path;
		}else{
			return dirname($path).'/big/'.basename($path);
		}
	}
	public function getThumb($path){
		if(strpos($path,"/thumb")){
			return $path;
		}else{
			return dirname($path).'/thumb/'.basename($path);
		}
	}	
	public function getItemPic($typeID,$itemID){
		$imgDao = new DaoImage();
		$pic = $imgDao->getOne(" typeID ='".$typeID."' and itemID = '".$itemID."' order by id desc limit 1");
		return $pic;
	}
	public function savePhoto($x,$y,$path){
		$filePath = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.date('Ymd').'/thumb';
		$path = $_SERVER['DOCUMENT_ROOT'].$path;
		$fileParts = pathinfo($path);
		$targetFile = rtrim($filePath,'/').'/'.time().rand(0,9).strrchr($fileParts['name'],'.');
		$type = $fileParts['extension'];
		if($type=="jpg" || $type=='jpeg'){
			$tmpImg = imagecreatefromjpeg($path);
			$targetFile = $targetFile.".jpg";
		}elseif($type=="gif"){ 
			$tmpImg = imagecreatefromgif($path); 
			$targetFile = $targetFile.".gif";
		}elseif($type=="png" || $type=='x-png'){
			$tmpImg = imagecreatefrompng($path); 
			$targetFile = $targetFile.".png";
		}
		rare_mkdir($filePath);
		$width = imagesx($tmpImg);
		$height = imagesy($tmpImg);
		$thumbWidth = 271;
		$thumbHeight = 271;
		$newImg = imagecreatetruecolor($thumbWidth,$thumbHeight); 
		imagecopyresampled($newImg,$tmpImg,0,0,$x,$y,$thumbWidth,$thumbHeight,$thumbWidth,$thumbHeight);  
		imagejpeg($newImg,$targetFile);
		return str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
	}
}
?>
